# This is a sample Python script.

# Press ⌃R to execute it or replace it with your code.
# Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.

import cv2 as cv
import numpy as np
import point
import math


def resize_img(image, height=1800):
    h, w = image.shape[:2]
    pro = height / h
    s_w = int(w * pro)
    s_h = int(height)
    size = (s_w, s_h)
    img = cv.resize(image, size)
    return img


def get_len(point1, point2):
    p1 = np.array(point1)
    p2 = np.array(point2)
    p3 = p2 - p1
    p4 = math.hypot(p3[0], p3[1])
    return p4


def angle(v1, v2):
    dx1 = v1[2] - v1[0]
    dy1 = v1[3] - v1[1]
    dx2 = v2[2] - v2[0]
    dy2 = v2[3] - v2[1]
    angle1 = math.atan2(dy1, dx1)
    angle1 = int(angle1 * 180 / math.pi)
    angle2 = math.atan2(dy2, dx2)
    angle2 = int(angle2 * 180 / math.pi)
    # print(angle2)
    if angle1 * angle2 >= 0:
        included_angle = angle1 - angle2
    else:
        included_angle = abs(angle1) + abs(angle2)
        if included_angle > 180:
            included_angle = 360 - included_angle
    return included_angle


def first_step(src):
    # 灰度
    gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
    # 高斯平滑
    gray = cv.GaussianBlur(gray, (3, 3), sigmaX=5, sigmaY=5, borderType=cv.BORDER_DEFAULT)
    # 边缘检测
    gray = cv.Canny(gray, 25, 50, apertureSize=3, L2gradient=False)
    # 膨胀操作，尽量使边缘闭合
    kernel = np.ones((3, 3), np.uint8)
    gray = cv.dilate(gray, kernel, iterations=0)
    ret, thresh = cv.threshold(gray, 127, 255, cv.THRESH_BINARY)
    contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
    lt_coordinate = True
    rt_coordinate = True
    lb_coordinate = True
    rb_coordinate = True
    point_dict = {}
    for contour in contours:
        hull = cv.convexHull(contour)
        epsilon = 0.02 * cv.arcLength(contour, True)
        approx = cv.approxPolyDP(hull, epsilon, True)
        if len(approx) == 4:
            currentArea = cv.contourArea(approx)
            if 2400 < currentArea < 4000:
                x, y, w, h = cv.boundingRect(approx)
                p = point.Point(x, y, w, h)
                # cv.rectangle(src, (x, y), (x + w, y + h), (0, 255, 0), 2)
                if x <= 675:
                    if y <= 900 and lt_coordinate:
                        point_dict['lt'] = p
                        lt_coordinate = False
                    elif lb_coordinate:
                        point_dict['lb'] = p
                        lb_coordinate = False
                # else:
                #     if y <= 900 and rt_coordinate:
                #         point_dict['rt'] = p
                #         rt_coordinate = False
                #     elif rb_coordinate:
                #         point_dict['rb'] = p
                #         rb_coordinate = False

    # 确定四个角
    lt = point_dict['lt']
    lb = point_dict['lb']
    # rt = point_dict['rt']
    # rb = point_dict['rb']
    # cv.circle(src, (lt.x, lt.y), 5, (0, 255, 0), 2)
    # cv.circle(src, (lb.x, lb.y), 5, (0, 255, 0), 2)
    # cv.circle(src, (rt.x, rt.y), 5, (0, 255, 0), 2)
    # cv.circle(src, (rb.x, rb.y), 5, (0, 255, 0), 2)
    return lt, lb


path = '/Users/wanggh/Desktop/a.jpeg'
# path = '/Users/wanggh/Desktop/b.jpeg'
# path = '/Users/wanggh/Desktop/c.jpeg'
# path = '/Users/wanggh/Desktop/d.jpeg'
# path = '/Users/wanggh/Desktop/e.jpeg'
# path = '/Users/wanggh/Desktop/original.jpeg'
path = '/Users/wanggh/Desktop/b.jpeg'
src = cv.imread(path)
src = resize_img(src)
lt, lb = first_step(src)
# 计算夹角
a = angle([lt.x, lt.y, lb.x, lb.y], [lt.x, lt.y, lt.x, lb.y])
cv.circle(src, (lt.x, lt.y), 5, (0, 255, 0), 2)

# l = int(get_len((lt.x, lt.y), (lb.x, lb.y)))
# w = int(l * 0.76)
# print(l * 0.5, w * 0.5)
# 调整角度
height = 1800
width = 1350
matRotate = cv.getRotationMatrix2D((height * 0.5, width * 0.5), a, 0.5)  # mat rotate 1 center 2 angle 3 缩放系数
dst = cv.warpAffine(src, matRotate, (height, width))
# second_step(dst)
cv.imshow("test", src)
cv.waitKey(0)
cv.destroyAllWindows()
